package org.swift.commons.deployer.framework.axis2;

import java.util.*;

import javax.servlet.ServletRequest;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.swift.commons.deployer.security.UserInfo;
import org.swift.commons.deployer.security.UserInfoImpl;

public class MessageContextReader {
	
	private final static Log log = LogFactory.getLog(MessageContextReader.class);
	
	/**
	 * Create a UserInfo object for use with criterion/security
	 * @param attributes Map<String,Object> containing user attributes
	 * @return new UserInfo
	 */
	public UserInfo createUserInfo(Map<String,Object> attributes) {
		return new UserInfoImpl(attributes);
	}
	
	/**
	 * Pull map of user attributes off the message context
	 * @param context Axis MessageContext
	 * @return map of user attributes
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getUserAttributes(MessageContext context) {
		ServletRequest req = (ServletRequest) context
		.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
		Map<String, Object> map = new HashMap<String,Object>();
		Enumeration<String> attrs = req.getAttributeNames();
		while(attrs.hasMoreElements()){
			String name = attrs.nextElement();
			Object value = req.getAttribute(name);
			if(value instanceof HashSet){
				Iterator iterator = ((HashSet) value).iterator();
				if ( iterator.hasNext() ) {
					value = iterator.next();
				}
			}
			log.debug("Attribute: "+name+" Value: "+value);
			map.put(name, value);
		}
		//return (Map<String, Object>) req.getAttribute("USER_INFO");
		return map;
	}
	
	/**
	 * Pull the service url off the context and set <i>baseUrl</i> and <i>serviceUrl</i> on the context.
	 * baseUrl is the url up through /service while serviceUrl includes the service name.
	 * @param context Axis MessageContext
	 * @param map context map
	 */
	
	public void setUrlsOnContext(MessageContext context,Map<String, String> map){
		javax.servlet.http.HttpServletRequest req = 
			(javax.servlet.http.HttpServletRequest)context.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
		String serviceUrl = req.getRequestURL().toString();
		String baseUrl = serviceUrl.substring(0, serviceUrl.lastIndexOf("/services")+9);
		map.put("baseUrl", baseUrl);
		log.debug("Base URL: "+baseUrl);
		map.put("serviceUrl", serviceUrl);
		log.debug("Service URL: "+serviceUrl);
	}
}
